package com.train.common.flow.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.train.common.core.util.ApplicationContextHolder;
import com.train.common.flow.constant.FlowConstant;
import com.train.common.flow.model.FlowTaskExt;
import com.train.common.flow.object.AutoTaskConfig;
import com.train.common.flow.object.HttpRequestInfo;
import com.train.common.flow.object.HttpResponseData;
import com.train.common.flow.service.FlowTaskExtService;
import com.train.common.flow.util.FlowBusinessHelper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;

import java.util.ArrayList;
import java.util.List;

/**
 * 流程任务监听器，用于获取流程中指定节点的审批人员。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Slf4j
public class FlowGetApiUsersListener implements TaskListener {

    private final transient FlowTaskExtService flowTaskExtService =
            ApplicationContextHolder.getBean(FlowTaskExtService.class);
    private final transient FlowBusinessHelper flowBusinessHelper =
            ApplicationContextHolder.getBean(FlowBusinessHelper.class);

    @Override
    public void notify(DelegateTask delegateTask) {
        String definitionId = delegateTask.getProcessDefinitionId();
        String taskKey = delegateTask.getTaskDefinitionKey();
        FlowTaskExt taskExt = flowTaskExtService.getByProcessDefinitionIdAndTaskId(definitionId, taskKey);
        if (StrUtil.isBlank(taskExt.getApiJson())) {
            return;
        }
        HttpConfig httpConfig = JSON.parseObject(taskExt.getApiJson(), HttpConfig.class);
        List<AutoTaskConfig.ValueInfo> headers = httpConfig.getHttpRequestInfo().getHeaderList();
        if (headers == null) {
            headers = new ArrayList<>();
        }
        headers.add(AutoTaskConfig.ValueInfo.buildWithFixValue("taskId", delegateTask.getTaskDefinitionKey()));
        httpConfig.getHttpRequestInfo().setHeaderList(headers);
        JSONObject variableData = flowBusinessHelper.getNonRealtimeSystemVariables();
        variableData.putAll(delegateTask.getVariables());
        String candidateUsers =
                flowBusinessHelper.requestHttpApi(httpConfig.httpRequestInfo, httpConfig.httpResponnseData, variableData);
        if (StrUtil.isBlank(candidateUsers)) {
            delegateTask.setAssignee(variableData.getString(FlowConstant.PROC_INSTANCE_START_USER_NAME_VAR));
        } else {
            delegateTask.addCandidateUsers(StrUtil.split(candidateUsers, StrUtil.COMMA));
        }
    }

    @Data
    static class HttpConfig {
        private HttpRequestInfo httpRequestInfo;
        private HttpResponseData httpResponnseData;
    }
}
